
package com.multimedia.room.fragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Date;
import android.widget.Toast;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import android.os.Message;
import com.mmclass.libsiren.net.FormFile;
import com.mmclass.libsiren.net.SocketHttpRequester;
import com.multimedia.room.BaseFragment;
import com.multimedia.room.CommandManager;
import com.multimedia.room.CommonUtil;
import com.multimedia.room.ISwitch;
import com.multimedia.room.MediaMessage;
import com.multimedia.room.R;
import com.multimedia.room.SwitchManager;
import com.multimedia.room.urlhttp.CallBackUtil;
import com.multimedia.room.urlhttp.UrlHttpUtil;
import org.json.JSONException;
import org.json.JSONObject;
public class TeachDictationFragment extends BaseFragment implements TextWatcher, ISwitch {
    private String mDictationResult = "";
    private static final String TAG = TeachDictationFragment.class.getSimpleName();
    private static Object moBjectLock = new Object();
    private EditText mDictationView;
    private TextView mOverView;
    private SwitchManager mSwitchManager;
    private String mBasePath;
    private static final String mExamPath = "mmclassexam/";
    private static final String mExamName = "dictation";
    private static String mFloderPath;
    private static  String mFileName;
    private static String mUploadUrl;

   static Handler mHandler = new MsgHandler();
    public static TeachDictationFragment newInstance(MediaMessage message) {
        mUploadUrl = message.getParams();
        TeachDictationFragment fragment = new TeachDictationFragment();
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.teach_dictation_layout, null);
        mDictationView = (EditText) rootView.findViewById(R.id.dictation_context);
        mDictationView.addTextChangedListener(this);
        mOverView = (TextView) rootView.findViewById(R.id.dictation_over);
        mOverView.setVisibility(View.GONE);
        mSwitchManager = SwitchManager.getInstance();
        mSwitchManager.registerDictationSwitch(this);
        mBasePath = this.getActivity().getFilesDir().getAbsolutePath();
        mFloderPath = mBasePath + File.separator + mExamPath;
        mFileName = CommonUtil.getSeatNo() + "_" + mExamName
                + ".txt";
        return rootView;
    }

    @Override
    public void afterTextChanged(Editable s) {
        mDictationResult = s.toString();

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mSwitchManager.unregisterDictationSwitch(this);

    }

    @Override
    public void switchOn(String params) {
        Log.d(TAG, "switchOn "+ params);
        mDictationView.setEnabled(true);
//      CommandManager.closeMic();
        CommandManager.closeMic();
        mOverView.setVisibility(View.GONE);
    }

    @Override
    public void switchOff(String params) {
        Log.d(TAG, "switchOff "+params);
        // stop dictation
        CommandManager.closeMic();
        mOverView.setVisibility(View.VISIBLE);
        mDictationView.setEnabled(false);
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                writeFile(mFileName, mDictationResult.trim());
                uploadFile(mFileName);
            }
        });
//        CommandManager.sendDictationMessage(encode(mDictationResult));

    }

    @Override
    public void broadcastOn(String params) {

    }

    @Override
    public void brocadOff(String params) {

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    /*
 * 16进制数字字符集
 */
    private static String hexString = "0123456789ABCDEF";

    /*
     * 将字符串编码成16进制数字,适用于所有字符（包括中文）
     */
    public static String encode(String str) {
        // 根据默认编码获取字节数组
        byte[] bytes = str.getBytes();
        StringBuilder sb = new StringBuilder(bytes.length * 2);
        // 将字节数组中每个字节拆解成2位16进制整数
        for (int i = 0; i < bytes.length; i++) {
            sb.append(hexString.charAt((bytes[i] & 0xf0) >> 4));
            sb.append(hexString.charAt((bytes[i] & 0x0f) >> 0));
        }
        return sb.toString();
    }

    /*
     * 将16进制数字解码成字符串,适用于所有字符（包括中文）
     */
    public static String decode(String bytes) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(
                bytes.length() / 2);
        // 将每2位16进制整数组装成一个字节
        for (int i = 0; i < bytes.length(); i += 2)
            baos.write((hexString.indexOf(bytes.charAt(i)) << 4 | hexString
                    .indexOf(bytes.charAt(i + 1))));
        return new String(baos.toByteArray());
    }

    private void writeFile(String fileName, String content) {
        File floder = new File(mFloderPath);
        File file = new File(mFloderPath + File.separator + fileName);
        if (floder.exists()) {
            // Nothing to do
        } else {
            floder.mkdirs();
        }
        if (file.exists())
            file.delete();
        try {
            file.createNewFile();
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
            osw.write(content);
            osw.flush();
        } catch (IOException e) {
            throw new IllegalStateException("Failed to create " + file.toString());
        }
    }

    private void uploadFile() {
            Message msg = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
            msg.obj=mFileName;
            mHandler.sendMessageDelayed(msg,1000);
    }

    private static boolean uploadFile(final String fileName) {
        final File file = new File(mFloderPath, fileName);
        if(!file.exists()){
            Log.d(TAG, "upload file failed due to "+ fileName +" doesn't exits");
            return false;
        }
        CommonUtil.changeMode(mFloderPath);
        CommonUtil.changeMode(file.getAbsolutePath());
        FormFile formfile = new FormFile(fileName, file, "file",
                "application/octet-stream");

        Log.d(TAG,
                "upload start " + mUploadUrl + " === "
                        + fileName
                        + new Date(System.currentTimeMillis())
                        .toString());
        if (file == null) {
                     Toast.makeText(mContext, "uploadFile failed file is null , return ", Toast.LENGTH_SHORT).show();
            Log.e(TAG, " uploadFile failed file is null , return ");
            return false;
        }


        if (formfile == null) {
                    Toast.makeText(mContext, "uploadFile failed formfile is null , return", Toast.LENGTH_SHORT).show();

            Log.e(TAG, " uploadFile failed formfile is null , return ");
            return false;
        }

        UrlHttpUtil.uploadFile(mUploadUrl, file, "file", UrlHttpUtil.FILE_TYPE_FILE, new CallBackUtil.CallBackString() {


            @Override
            public void onFailure(int code, String errorMessage) {
                Log.i(TAG, "code " + code + " errorMessage " + errorMessage);
                try {
                    throw new Exception("uploadFile failed");
                } catch (Exception e) {
                    Log.e(TAG, "uploadFile failed ", e);
                }
            }

            @Override
            public void onResponse(String response) {
                Log.i(TAG, "onResponse " + response);
                try {
                    JSONObject rootJson = new JSONObject(response);
                    if (rootJson != null && rootJson.has("Code")) {
                        int code = rootJson.getInt("Code");
                        if (0 == code) {
                            Log.i(TAG, "upload successful " + file.getName());
                             File tmp = new File(mFloderPath + File.separator + file.getName());
			    if(tmp.isFile()){
                                tmp.delete();
                                Log.i(TAG, "upload successful delete local file" + file.getName());
                            }

                        } else {
                            uploadFile();
                            try {
                                throw new Exception("uploadFile failed");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        Log.d(TAG,
                "upload end " + mUploadUrl + " === "
                        + fileName
                        + new Date(System.currentTimeMillis())
                        .toString());
        CommandManager.sendUpdateCompletionMessage();
        return true;


    }
 static class MsgHandler extends Handler {
        static final int UPLOAD_FILE = 1;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            synchronized (moBjectLock) {
                final String fileName = (String) msg.obj;
                Log.e(TAG, " handleMessage  msg.what = " + msg.what + " UPLOAD_FILE = " + fileName );
                if (UPLOAD_FILE == msg.what) {
                    try {
                        uploadFile(fileName);
                    } catch (Exception e) {
                        Log.e(TAG, " uploadFile failed retry again!", e);
                        Message msg1 = mHandler.obtainMessage(MsgHandler.UPLOAD_FILE);
                        msg1.obj = fileName;
                        mHandler.sendMessageDelayed(msg1, 1000);
                    }
                } 
            }
        }
    }



}
